package cn.wolfcode.crm.service.imp;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.qo.PageResult;
import cn.wolfcode.crm.qo.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void saveOrUpdate(Role entity, Long[] menuIds) {
        if (entity.getId() != null) {
            roleMapper.updateByPrimaryKey(entity);
            //删除关系,插入关系
                roleMapper.deleteRelation(entity.getId());
                roleMapper.deleteRelationMenu(entity.getId());


        } else {
            roleMapper.insert(entity);
        }
        if (menuIds != null ) {
            for (Long menuId : menuIds) {

        roleMapper.insertRelationMenu(entity.getId(),menuId);
            }
        }

        if (entity.getPermissions()  != null) {
            for (Permission p : entity.getPermissions()) {

        roleMapper.insertRelation(entity.getId(),p.getId());
            }
        }

    }

    @Override
    public void delete(Long id) {
        if (id != null) {
            roleMapper.deleteRelation(id);
            roleMapper.deleteRelationMenu(id);

            roleMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public Role get(Long id) {

            Role entity = roleMapper.selectByPrimaryKey(id);
        System.out.println(66);
        return entity;

    }

    @Override
    public List<Role> selectAll() {
        List<Role> depts = roleMapper.selectAll();
        return depts;
    }

    @Override
    //通过角色查询菜单
    public Long[] selectMenuByRoleId(Long id) {

        return roleMapper.selectMenuByRoleId(id);
    }

    @Override
    //通过角色查询权限
    public Long[] selectPermissionById(Long id) {
        return roleMapper.selectPermissionById(id);

    }

    //通过员工id查询角色
    public List<Role> selectSnByEmployeeId(Long id) {
        List<Role> roles = roleMapper.selectByEmployeeId(id);
        return roles;
    }

    @Override
    public PageResult queryForList(QueryObject qo) {
        int rows = roleMapper.rows(qo);
        if (rows == 0) {
            return PageResult.EMPTY_RESULT;
        }
        PageResult result =   new PageResult(rows,roleMapper.queryForList(qo));

        return result;

    }
}
